import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;


public class ClientListener implements Runnable {

	protected ClientLogic logic;
	protected ServerSocket socket;
	
	public ClientListener() throws IOException {
		socket = new ServerSocket(0);
		logic = new ClientLogic();
		logic.localPort = socket.getLocalPort();
		System.out.print("Listening on port ");
		System.out.println(socket.getLocalPort());
	}
	
	@Override
	public void run() {
		System.out.println("Listener Start");
		BufferedReader in = null;
		String line;
		Socket remote;
		
		//Main loop
		while (true) {
			try {
				remote = socket.accept();
				in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
				
				line = in.readLine();
				System.out.println("#>"+line);
				
				switch(line) {
				case "message":		message(in);	break;
				case "online":		online(in);	break;
				case "offline":		offline(in.readLine());	break;
				
				default:
					//unknown message. Discard.
					System.out.println("Unknown msg:");
					System.out.println(line);
					break;
				}
				in.close();
				remote.close();
				remote = null;
				//And back around for the next connection
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void offline(String user) {
		System.out.println("LOGOFF "+user);
		logic.offline(user);
	}
	
	private void online(BufferedReader in) throws NumberFormatException, IOException {
		String user = in.readLine();
		String host = in.readLine();
		int port = Integer.parseInt(in.readLine());
		
		System.out.println("LOGIN "+user);
		logic.online(user, host, port);
	}
	
	private void message(BufferedReader in) {
		try {
			String user = in.readLine();
			if(user==null) return;
			String msg = "";
			String line = "";
			while((line = in.readLine()) != null) {
				msg += line;
			}
			
			logic.receiveChatMessage(user, msg);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
